// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //通过JS的方法获取当前年月日
  var date = new Date();
  date = new Date(date.getTime() + 8 * 60 * 60 * 1000);

  let yes_Y = 0;
  let yes_M = "";
  let yes_D = 0;

  var yes = null;
  while (true) {
    date = new Date(date.setTime(date.getTime() - 24 * 60 * 60 * 1000));
    //获取昨天?年份  
    yes_Y = date.getFullYear();
    //获取昨天?月份  
    yes_M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取昨天?日期 
    yes_D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    yes = await db.collection('location').where({ //yes：昨天的数据
      user_id: event.openid,
      time: {
        year: yes_Y,
        month: yes_M,
        day: yes_D,
      }
    }).get();
    if (yes.data[0] != null) break;
  }
  return {
    word_id: yes.data[0].word_id,
    time: {
      year: yes.data[0].time.year,
      month: yes.data[0].time.month,
      day: yes.data[0].time.day,
    }
  }
}